home *** CD-ROM | disk | FTP | other *** search
/ Atari Mega Archive 1 / Atari Mega Archive - Volume 1.iso / gnu / bash / bash_110 / mint / bash110s.zoo / bash-1.10 / jobs.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-09-30  |  53.5 KB  |  2,282 lines

  1. /* The thing that makes children, remembers them, and contains wait loops. */
  2.  
  3. /* This file works with both POSIX and BSD systems. */
  4.  
  5. /* Copyright (C) 1989 Free Software Foundation, Inc.
  6.  
  7. This file is part of GNU Bash, the Bourne Again SHell.
  8.  
  9. Bash is free software; you can redistribute it and/or modify it under
  10. the terms of the GNU General Public License as published by the Free
  11. Software Foundation; either version 1, or (at your option) any later
  12. version.
  13.  
  14. Bash is distributed in the hope that it will be useful, but WITHOUT ANY
  15. WARRANTY; without even the implied warranty of MERCHANTABILITY or
  16. FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  17. for more details.
  18.  
  19. You should have received a copy of the GNU General Public License along
  20. with Bash; see the file COPYING.  If not, write to the Free Software
  21. Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
  22.  
  23. /* Something that can be ignored. */
  24. #define IGNORE_ARG (char *)0
  25.  
  26. #include "config.h"
  27.  
  28. #if !defined (JOB_CONTROL)
  29. #include "nojobs.c"
  30. #else /* JOB_CONTROL */
  31.  
  32. #include "trap.h"
  33. #include <stdio.h>
  34. #include <signal.h>
  35. #include <errno.h>
  36. #include <sys/types.h>
  37.  
  38. #if !defined (USG) || defined (HAVE_RESOURCE)
  39. #include <sys/time.h>
  40. #endif /* USG */
  41.  
  42. #if !defined (_POSIX_VERSION)
  43. #  if defined (HAVE_RESOURCE)
  44. #    include <sys/resource.h>
  45. #  endif
  46. #endif /* _POSIX_VERSION */
  47.  
  48. #include <sys/file.h>
  49. #include <sys/ioctl.h>
  50. #include <sys/param.h>
  51. #include "filecntl.h"
  52.  
  53. /* Terminal handling stuff, to save and restore tty state. */
  54. #define NEW_TTY_DRIVER
  55.  
  56. /* Define this if your output is getting swallowed.  It's a no-op on
  57.    machines with the termio or termios tty drivers. */
  58. /* #define DRAIN_OUTPUT */
  59.  
  60. #if defined (_POSIX_VERSION) && !defined (TERMIOS_MISSING)
  61. #  undef NEW_TTY_DRIVER
  62. #  define TERMIOS_TTY_DRIVER
  63. #  if defined (sun)
  64. #    define _POSIX_SOURCE
  65. #  endif
  66. #else /* !_POSIX_VERSION */
  67. #  if defined (USG) || defined (hpux) || defined (Xenix) || defined (sgi)
  68. #    undef NEW_TTY_DRIVER
  69. #    define TERMIO_TTY_DRIVER
  70. #  endif /* USG | hpux | Xenix | sgi */
  71. #endif /* !_POSIX_VERSION */
  72.  
  73. /* Include the right header file for the specific type of terminal
  74.    handler installed on this system. */
  75. #if defined (NEW_TTY_DRIVER)
  76. #include <sgtty.h>
  77. #endif
  78.  
  79. #if defined (TERMIO_TTY_DRIVER)
  80. #include <termio.h>
  81. #endif
  82.  
  83. #if defined (TERMIOS_TTY_DRIVER)
  84. #include <termios.h>
  85. #endif
  86.  
  87. /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
  88.  
  89. #if defined (hpux) && !defined (TERMIOS_TTY_DRIVER)
  90. #include <bsdtty.h>
  91. #endif /* hpux && !TERMIOS_TTY_DRIVER */
  92.  
  93. #include "shell.h"
  94. #include "jobs.h"
  95.  
  96. /* Not all systems define errno in errno.h. */
  97. extern int errno;
  98. extern int interactive;
  99. extern char *shell_name;
  100. extern char *sys_siglist[];
  101.  
  102. /* The array of known jobs. */
  103. JOB **jobs = (JOB **)NULL;
  104.  
  105. /* The number of slots currently allocated to JOBS. */
  106. int job_slots = 0;
  107.  
  108. /* The number of additional slots to allocate when we run out. */
  109. #define JOB_SLOTS 5
  110.  
  111. /* The controlling tty for this shell. */
  112. int shell_tty = -1;
  113.  
  114. /* The shell's process group. */
  115. pid_t shell_pgrp = NO_PID;
  116.  
  117. /* The terminal's process group. */
  118. pid_t terminal_pgrp = NO_PID;
  119.  
  120. /* The process group of the shell's parent. */
  121. pid_t original_pgrp = NO_PID;
  122.  
  123. /* The process group of the pipeline currently being made. */
  124. pid_t pipeline_pgrp = (pid_t)0;
  125.  
  126. #if defined (PGRP_PIPE)
  127. /* Pipes which each shell uses to communicate with the process group leader
  128.    until all of the processes in a pipeline have been started.  Then the
  129.    process leader is allowed to continue. */
  130. int pgrp_pipe[2] = { -1, -1 };
  131. #endif
  132.       
  133. /* The job which is current; i.e. the one that `%+' stands for. */
  134. int current_job = NO_JOB;
  135.  
  136. /* The previous job; i.e. the one that `%-' stands for. */
  137. int previous_job = NO_JOB;
  138.  
  139. /* Last child made by the shell.  */
  140. pid_t last_made_pid = NO_PID;
  141.  
  142. /* Pid of the last asynchronous child. */
  143. pid_t last_asynchronous_pid = NO_PID;
  144.  
  145. /* Non-zero allows asynchronous job notification.  If not set,
  146.    then job state notification only takes place just before a
  147.    prompt is printed. */
  148. int asynchronous_notification = 0;
  149.  
  150. /* The pipeline currently being built. */
  151. PROCESS *the_pipeline = (PROCESS *)NULL;
  152.  
  153. /* If this is non-zero, do job control. */
  154. int job_control = 1;
  155.  
  156. /* Call this when you start making children. */
  157. int already_making_children = 0;
  158.  
  159. /* Functions local to this file. */
  160. static sighandler flush_child ();
  161. static PROCESS *find_pipeline ();
  162. static char *job_working_directory ();
  163. static pid_t last_pid ();
  164. static int set_new_line_discipline (), map_over_jobs (), last_running_job ();
  165. static int most_recent_job_in_state (), last_stopped_job (), find_job ();
  166. static void notify_of_job_status (), cleanup_dead_jobs (), discard_pipeline ();
  167. static void add_process (), set_current_job (), reset_current ();
  168. static void pretty_print_job ();
  169. #if defined (PGRP_PIPE)
  170. static void pipe_read (), pipe_close ();
  171. #endif
  172.  
  173. #if !defined (_POSIX_VERSION)
  174.  
  175. /* These are definitions to map POSIX 1003.1 functions onto existing BSD
  176.    library functions and system calls. */
  177. #define setpgid(pid, pgrp)    setpgrp (pid, pgrp)
  178. #define tcsetpgrp(fd, pgrp)    ioctl ((fd), TIOCSPGRP, &(pgrp))
  179.  
  180. pid_t
  181. tcgetpgrp (fd)
  182.      int fd;
  183. {
  184.   pid_t pgrp;
  185.  
  186.   /* ioctl will handle setting errno correctly. */
  187.   if (ioctl (fd, TIOCGPGRP, &pgrp) < 0)
  188.     return (-1);
  189.   return (pgrp);
  190. }
  191.  
  192. /* Perform OPERATION on NEWSET, perhaps leaving information in OLDSET. */
  193. sigprocmask (operation, newset, oldset)
  194.      int operation, *newset, *oldset;
  195. {
  196.   switch (operation)
  197.     {
  198.     case SIG_BLOCK:
  199.       *oldset = sigblock (*newset);
  200.       break;
  201.  
  202.     case SIG_SETMASK:
  203.       sigsetmask (*newset);
  204.       break;
  205.  
  206.     default:
  207.       report_error ("Bad code in jobs.c: sigprocmask");
  208.     }
  209. }
  210. #endif /* !_POSIX_VERSION */
  211.  
  212. /* Return the working directory for the current process. */
  213. static char *
  214. job_working_directory ()
  215. {
  216.   extern char *get_working_directory ();
  217.   char *dir;
  218.  
  219.   dir = get_string_value ("PWD");
  220.   if (dir)
  221.     return (savestring (dir));
  222.  
  223.   dir = get_working_directory ("");
  224.   if (dir)
  225.     return (dir);
  226.  
  227.   return (savestring ("<unknown>"));
  228. }
  229.  
  230. making_children ()
  231. {
  232.   if (already_making_children)
  233.     return;
  234.  
  235.   already_making_children = 1;
  236.   start_pipeline ();
  237. }
  238.  
  239. stop_making_children ()
  240. {
  241.   already_making_children = 0;
  242. }
  243.  
  244. /* Start building a pipeline.  */
  245. start_pipeline ()
  246. {
  247.   if (the_pipeline)
  248.     {
  249.       discard_pipeline (the_pipeline);
  250.       the_pipeline = (PROCESS *)NULL;
  251.       pipeline_pgrp = 0;
  252. #if defined (PGRP_PIPE)
  253.       pipe_close (pgrp_pipe);
  254. #endif
  255.     }
  256.  
  257. #if defined (PGRP_PIPE)
  258.   if (job_control)
  259.     {
  260.       if (pipe (pgrp_pipe) == -1)
  261.     report_error ("start_pipeline: pgrp pipe");
  262.     }
  263. #endif
  264. }
  265.  
  266. /* Stop building a pipeline.  Install the process list in the job array.
  267.    This returns the index of the newly installed job.
  268.    DEFERRED is a command structure to be executed upon satisfactory
  269.    execution exit of this pipeline. */
  270. int
  271. stop_pipeline (async, deferred)
  272.      int async;
  273.      COMMAND *deferred;
  274. {
  275.   register int i, j;
  276.   JOB *newjob = (JOB *)NULL;
  277.   char *get_string_value ();
  278.   sigset_t set, oset;
  279.  
  280.   BLOCK_CHILD (set, oset);
  281.  
  282. #if defined (PGRP_PIPE)
  283.   /* The parent closes the process group synchronization pipe. */
  284.   pipe_close (pgrp_pipe);
  285. #endif
  286.     
  287.   cleanup_dead_jobs ();
  288.  
  289.   if (!job_slots)
  290.     {
  291.       jobs =
  292.     (JOB **)xmalloc ((job_slots = JOB_SLOTS) * sizeof (JOB *));
  293.  
  294.       /* Now blank out these new entries. */
  295.       for (i = 0; i < job_slots; i++)
  296.     jobs[i] = (JOB *)NULL;
  297.     }
  298.  
  299.   /* Scan from the last slot backward, looking for the next free one. */
  300.   for (i = job_slots; i; i--)
  301.     if (jobs[i - 1])
  302.       break;
  303.  
  304.   /* Do we need more room? */
  305.   if (i == job_slots)
  306.     {
  307.       jobs = (JOB **)realloc
  308.     (jobs, (1 + (job_slots += JOB_SLOTS)) * sizeof (JOB *));
  309.  
  310.       for (j = i; j < job_slots; j++)
  311.     jobs[j] = (JOB *)NULL;
  312.     }
  313.  
  314.   /* Add the current pipeline to the job list. */
  315.   if (the_pipeline)
  316.     {
  317.       register PROCESS *p;
  318.  
  319.       newjob = (JOB *)xmalloc (sizeof (JOB));
  320.  
  321.       for (p = the_pipeline; p->next != the_pipeline; p = p->next);
  322.       p->next = (PROCESS *)NULL;
  323.       newjob->pipe = (PROCESS *)reverse_list (the_pipeline);
  324.       for (p = newjob->pipe; p->next; p = p->next);
  325.       p->next = newjob->pipe;
  326.  
  327.       the_pipeline = (PROCESS *)NULL;
  328.       newjob->pgrp = pipeline_pgrp;
  329.       pipeline_pgrp = 0;
  330.  
  331.       /* Flag to see if in another pgrp. */
  332.       newjob->job_control = job_control;
  333.  
  334.       /* Set the state of this pipeline. */
  335.       {
  336.     register PROCESS *p = newjob->pipe;
  337.     register int any_alive = 0;
  338.     register int any_stopped = 0;
  339.  
  340.     do
  341.       {
  342.         any_alive |= p->running;
  343.         any_stopped |= WIFSTOPPED (p->status);
  344.         p = p->next;
  345.       }
  346.     while (p != newjob->pipe);
  347.  
  348.     if (any_alive)
  349.       {
  350.         newjob->state = JRUNNING;
  351.       }
  352.     else
  353.       {
  354.         if (any_stopped)
  355.           newjob->state = JSTOPPED;
  356.         else
  357.           newjob->state = JDEAD;
  358.       }
  359.       }
  360.  
  361.       newjob->notified = 0;
  362.       newjob->wd = job_working_directory ();
  363.       newjob->deferred = deferred;
  364.  
  365.       jobs[i] = newjob;
  366.     }
  367.  
  368.   if (async)
  369.     {
  370.       if (newjob)
  371.     newjob->foreground = 0;
  372.       reset_current ();
  373.     }
  374.   else
  375.     {
  376.       if (newjob)
  377.     {
  378.       newjob->foreground = 1;
  379.       /*
  380.        *        !!!!! NOTE !!!!!  (chet@ins.cwru.edu)
  381.        *
  382.        * The currently-accepted job control wisdom says to set the
  383.        * terminal's process group n+1 times in an n-step pipeline:
  384.        * once in the parent and once in each child.  This is where
  385.        * the parent gives it away.
  386.        *
  387.        */
  388.       if (job_control && newjob->pgrp)
  389.         give_terminal_to (newjob->pgrp);
  390.     }
  391.     }
  392.  
  393.   stop_making_children ();
  394.   UNBLOCK_CHILD (oset);
  395.   return (current_job);
  396. }
  397.  
  398. /* Delete all DEAD jobs that the user had received notification about. */
  399. static void
  400. cleanup_dead_jobs ()
  401. {
  402.   register int i;
  403.   sigset_t set, oset;
  404.  
  405.   BLOCK_CHILD (set, oset);
  406.  
  407.   for (i = 0; i < job_slots; i++)
  408.     if (jobs[i] && JOBSTATE (i) == JDEAD && jobs[i]->notified)
  409.       delete_job (i);
  410.  
  411.   UNBLOCK_CHILD (oset);
  412. }
  413.  
  414. /* Delete the job at INDEX from the job list. */
  415. delete_job (index)
  416.      int index;
  417. {
  418.   register JOB *temp = jobs[index];
  419.  
  420.   if (index == current_job || index == previous_job)
  421.     reset_current ();
  422.  
  423.   jobs[index] = (JOB *)NULL;
  424.  
  425.   free (temp->wd);
  426.   discard_pipeline (temp->pipe);
  427.  
  428.   if (temp->deferred)
  429.     dispose_command (temp->deferred);
  430.  
  431.   free (temp);
  432. }
  433.  
  434. /* Get rid of the data structure associated with a process chain. */
  435. static void
  436. discard_pipeline (chain)
  437.      register PROCESS *chain;
  438. {
  439.   register PROCESS *this, *next;
  440.  
  441.   this = chain;
  442.   do
  443.     {
  444.       next = this->next;
  445.       if (this->command)
  446.     free (this->command);
  447.       free (this);
  448.       this = next;
  449.     }
  450.   while (this != chain);
  451. }
  452.  
  453. /* Add this process to the chain being built in the_pipeline.
  454.    NAME is the command string that will be exec'ed later.
  455.    PID is the process id of the child. */
  456. static void
  457. add_process (name, pid)
  458.      char *name;
  459.      pid_t pid;
  460. {
  461.   PROCESS *t = (PROCESS *)xmalloc (sizeof (PROCESS));
  462.  
  463.   t->next = the_pipeline;
  464.   t->pid = pid;
  465.   WSTATUS (t->status) = 0;
  466.   t->running = 1;
  467.   t->command = name;
  468.   the_pipeline = t;
  469.  
  470.   if (!(t->next))
  471.     t->next = t;
  472.   else
  473.     {
  474.       register PROCESS *p = t->next;
  475.  
  476.       while (p->next != t->next) p = p->next;
  477.       p->next = t;
  478.     }
  479. }
  480.  
  481. /* Map FUNC over the list of jobs.  If FUNC returns non-zero,
  482.    then it is time to stop mapping, and that is the return value
  483.    for map_over_jobs.  FUNC is called with a JOB, arg1, arg2,
  484.    and INDEX. */
  485. static int
  486. map_over_jobs (func, arg1, arg2)
  487.      Function *func;
  488. {
  489.   register int i;
  490.  
  491.   for (i = 0; i < job_slots; i++)
  492.     {
  493.       if (jobs[i])
  494.     {
  495.       int result = (*func)(jobs[i], arg1, arg2, i);
  496.       if (result)
  497.         return (result);
  498.     }
  499.     }
  500.   return (0);
  501. }
  502.  
  503. /* Cause all the jobs in the current pipeline to exit. */
  504. terminate_current_pipeline ()
  505. {
  506.   if (pipeline_pgrp && pipeline_pgrp != shell_pgrp)
  507.     {
  508.       killpg (pipeline_pgrp, SIGTERM);
  509.       killpg (pipeline_pgrp, SIGCONT);
  510.     }
  511. }
  512.  
  513. /* Cause all stopped jobs to exit. */
  514. void
  515. terminate_stopped_jobs ()
  516. {
  517.   register int i;
  518.  
  519.   for (i = 0; i < job_slots; i++)
  520.     {
  521.       if (jobs[i] && (JOBSTATE (i) == JSTOPPED))
  522.     {
  523.       killpg (jobs[i]->pgrp, SIGTERM);
  524.       killpg (jobs[i]->pgrp, SIGCONT);
  525.     }
  526.     }
  527. }
  528.  
  529. /* Cause all jobs, running or stopped, to receive a hangup signal. */
  530. void
  531. hangup_all_jobs ()
  532. {
  533.   register int i;
  534.  
  535.   for (i = 0; i < job_slots; i++)
  536.     {
  537.       if (jobs[i])
  538.     {
  539.       killpg (jobs[i]->pgrp, SIGHUP);
  540.       if (JOBSTATE (i) == JSTOPPED)
  541.         killpg (jobs[i]->pgrp, SIGCONT);
  542.     }
  543.     }
  544. }
  545.  
  546. kill_current_pipeline ()
  547. {
  548.   stop_making_children ();
  549.   start_pipeline ();
  550. }
  551.  
  552. /* Return the pipeline that PID belongs to.  Note that the pipeline
  553.    doesn't have to belong to a job. */
  554. static PROCESS *
  555. find_pipeline (pid)
  556.      pid_t pid;
  557. {
  558.   int job;
  559.  
  560.   /* See if this process is in the pipeline that we are building. */
  561.   if (the_pipeline)
  562.     {
  563.       register PROCESS *p = the_pipeline;
  564.  
  565.       do
  566.     {
  567.       /* Return it if we found it. */
  568.       if (p->pid == pid)
  569.         return (p);
  570.  
  571.       p = p->next;
  572.     }
  573.       while (p != the_pipeline);
  574.     }
  575.  
  576.   job = find_job (pid);
  577.  
  578.   if (job == NO_JOB)
  579.     return ((PROCESS *)NULL);
  580.   else
  581.     return (jobs[job]->pipe);
  582. }
  583.  
  584. /* Return the job index that PID belongs to, or NO_JOB if it doesn't
  585.    belong to any job. */
  586. static int
  587. find_job (pid)
  588.      pid_t pid;
  589. {
  590.   register int i;
  591.   register PROCESS *p;
  592.  
  593.   for (i = 0; i < job_slots; i++)
  594.     {
  595.       if (jobs[i])
  596.     {
  597.       p = jobs[i]->pipe;
  598.  
  599.       do
  600.         {
  601.           if (p->pid == pid)
  602.         return (i);
  603.  
  604.           p = p->next;
  605.         }
  606.       while (p != jobs[i]->pipe);
  607.     }
  608.     }
  609.  
  610.   return (NO_JOB);
  611. }
  612.  
  613. /* Print descriptive information about the job with leader pid PID. */
  614. describe_pid (pid)
  615.      pid_t pid;
  616. {
  617.   int job;
  618.   sigset_t set, oset;
  619.  
  620.   BLOCK_CHILD (set, oset);
  621.  
  622.   job = find_job (pid);
  623.  
  624.   if (job != NO_JOB)
  625.     printf ("[%d] %d\n", job + 1, pid);
  626.   else
  627.     programming_error ("describe_pid: No such pid (%d)!\n", pid);
  628.  
  629.   UNBLOCK_CHILD (oset);
  630. }
  631.  
  632. /* This is the way to print out information on a job if you
  633.    know the index.  FORMAT is:
  634.  
  635.     JLIST_NORMAL)   [1]+ Running       emacs
  636.     JLIST_LONG  )   [1]+ 2378 Running      emacs
  637.     -1      )   [1]+ 2378          emacs
  638.  
  639.     JLIST_NORMAL)   [1]+ Stopped       ls | more
  640.     JLIST_LONG  )   [1]+ 2369 Stopped      ls
  641.              2367        | more
  642.     JLIST_PID_ONLY)
  643.     Just list the pid of the process group leader (really
  644.     the process group).
  645.     JLIST_CHANGED_ONLY)
  646.     Use format JLIST_NORMAL, but list only jobs about which
  647.     the user has not been notified. */
  648. static void
  649. pretty_print_job (index, format, stream)
  650.      int index, format;
  651.      FILE *stream;
  652. {
  653.   register PROCESS *p, *first, *last;
  654.   int name_padding, list_not_notified_only = 0;
  655.   char retcode_name_buffer[20];
  656.   sigset_t set, oset;
  657.  
  658.   BLOCK_CHILD (set, oset);
  659.  
  660.   /* Format only pid information about the process group leader? */
  661.   if (format == JLIST_PID_ONLY)
  662.     {
  663.       fprintf (stream, "%d\n", jobs[index]->pipe->pid);
  664.       UNBLOCK_CHILD (oset);
  665.       return;
  666.     }
  667.  
  668.   if (format == JLIST_CHANGED_ONLY)
  669.     {
  670.       if (jobs[index]->notified == 1)
  671.     {
  672.       UNBLOCK_CHILD (oset);
  673.       return;
  674.     }
  675.       format = JLIST_STANDARD;
  676.     }
  677.  
  678.   fprintf (stream, "[%d]%c ", index + 1,
  679.        (index == current_job) ? '+':
  680.        (index == previous_job) ? '-' : ' ');
  681.  
  682.   first = last = p = jobs[index]->pipe;
  683.   while (last->next != first)
  684.     last = last->next;
  685.  
  686.   /* We have printed information about this job.  When the job's
  687.      status changes, flush_child () sets the notification flag to 0. */
  688.   jobs[index]->notified = 1;
  689.  
  690.   for (;;)
  691.     {
  692.       if (p != first)
  693.     fprintf (stream, format ? "     " : " |");
  694.  
  695.       if (format)
  696.     fprintf (stream, "%d", p->pid);
  697.  
  698.       fprintf (stream, " ");
  699.  
  700.       if (format > -1)
  701.     {
  702.       PROCESS *show = format ? p : last;
  703.       char *temp = "Done";
  704.  
  705.       if (JOBSTATE (index) == JSTOPPED && !format)
  706.         temp = "Stopped";
  707.  
  708.       if (JOBSTATE (index) == JRUNNING)
  709.         temp = "Running";
  710.       else
  711.         {
  712.         if (WIFSTOPPED (show->status))
  713.           temp = sys_siglist[WSTOPSIG (show->status)];
  714.         else if (WIFSIGNALED (show->status))
  715.           temp = sys_siglist[WTERMSIG (show->status)];
  716.         else if (WIFEXITED (show->status))
  717.           {
  718.             temp = retcode_name_buffer;
  719.             sprintf (temp, "Exit %d", WEXITSTATUS (show->status));
  720.           }
  721.         else
  722.           temp = "Unknown status";
  723.         }
  724.  
  725.       if (p != first)
  726.         {
  727.           if (format)
  728.         {
  729.           if (show->running == first->running &&
  730.               WSTATUS (show->status) == WSTATUS (first->status))
  731.             temp = "";
  732.         }
  733.           else
  734.         temp = (char *)NULL;
  735.         }
  736.  
  737.       if (temp)
  738.         {
  739.           fprintf (stream, "%s", temp);
  740.  
  741.           if (strlen (temp))
  742.         name_padding = LONGEST_SIGNAL_DESC - strlen (temp);
  743.           else
  744.         name_padding = LONGEST_SIGNAL_DESC - 2; /* strlen ("| ") */
  745.  
  746.           fprintf (stream, "%*s", name_padding, "");
  747.  
  748.           if ((!WIFSTOPPED (show->status)) && (WIFCORED (show->status)))
  749.         fprintf (stream, "(core dumped) ");
  750.         }
  751.     }
  752.  
  753.       if (p != first && format)
  754.     fprintf (stream, "| ");
  755.  
  756.       fprintf (stream, "%s", p->command);
  757.  
  758.       if (p == last) 
  759.     {
  760.       char *wd = job_working_directory ();
  761.  
  762.       if (JOBSTATE (index) == JRUNNING && jobs[index]->foreground == 0)
  763.         fprintf (stream, " &");
  764.  
  765.       if (strcmp (wd, jobs[index]->wd) != 0)
  766.         fprintf (stream,
  767.              "  (wd: %s)", polite_directory_format (jobs[index]->wd));
  768.       free (wd);
  769.     }
  770.  
  771.       if (format || (p == last))
  772.     fprintf (stream, "\r\n");
  773.  
  774.       if (p == last)
  775.     break;
  776.       p = p->next;
  777.     }
  778.  
  779.   fflush (stream);
  780.   UNBLOCK_CHILD (oset);
  781. }
  782.  
  783. int
  784. list_one_job (job, format, ignore, index)
  785.      JOB *job;
  786.      int format, ignore, index;
  787. {
  788.   pretty_print_job (index, format, stdout);
  789.   return (0);
  790. }
  791.  
  792. /* List jobs.  If FORMAT is non-zero, then the long form of the information
  793.    is printed, else just a short version. */
  794. list_jobs (format)
  795.      int format;
  796. {
  797.   cleanup_dead_jobs ();
  798.   map_over_jobs (list_one_job, format, (int)IGNORE_ARG);
  799. }
  800.  
  801. /* Fork, handling errors.  Returns the pid of the newly made child, or 0.
  802.    COMMAND is just for remembering the name of the command; we don't do
  803.    anything else with it.  ASYNC_P says what to do with the tty.  If
  804.    non-zero, then don't give it away. */
  805. pid_t
  806. make_child (command, async_p)
  807.      char *command;
  808.      int async_p;
  809. {
  810.   pid_t pid;
  811.   sigset_t set, oset;
  812.  
  813.   sigemptyset (&set);
  814.   sigaddset (&set, SIGCHLD);
  815.   sigaddset (&set, SIGINT);
  816.   sigemptyset (&oset);
  817.   sigprocmask (SIG_BLOCK, &set, &oset);
  818.  
  819.   making_children ();
  820.  
  821.   /* Make new environment array if neccessary. */
  822.   maybe_make_export_env ();
  823.  
  824.   /* Create the child, handle severe errors. */
  825.   if ((pid = fork ()) < 0)
  826.     {
  827.       /* Unblock SIGINT, SIGCHLD. */
  828.       sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
  829.  
  830.       report_error ("fork: %s", (char *)strerror (errno));
  831.  
  832.       /* Kill all of the processes in the current pipeline. */
  833.       terminate_current_pipeline ();
  834.  
  835.       /* Discard the current pipeline, if any. */
  836.       if (the_pipeline)
  837.     kill_current_pipeline ();
  838.  
  839.       throw_to_top_level ();
  840.     }
  841.  
  842.   if (!pid)
  843.     {
  844.       /* In the child.  Give this child the right process group, set the
  845.      signals to the default state for a new process. */
  846.       pid_t mine = getpid ();
  847.  
  848.       /* Cancel traps, in trap.c. */
  849.       restore_original_signals ();
  850.  
  851.       if (job_control)
  852.     {
  853.       /* All processes in this pipeline belong in the same
  854.          process group. */
  855.  
  856.       if (!pipeline_pgrp)    /* Then this is the first child. */
  857.         pipeline_pgrp = mine;
  858.  
  859.       /* Check for running command in backquotes. */
  860.       if (pipeline_pgrp == shell_pgrp)
  861.         {
  862.           signal (SIGTSTP, SIG_IGN);
  863.           signal (SIGTTOU, SIG_IGN);
  864.           signal (SIGTTIN, SIG_IGN);
  865.         }
  866.       else
  867.         {
  868.           signal (SIGTSTP, SIG_DFL);
  869.           signal (SIGTTOU, SIG_DFL);
  870.           signal (SIGTTIN, SIG_DFL);
  871.         }
  872.  
  873.       /* Set the process group before trying to mess with the terminal's
  874.          process group.  This is mandated by POSIX. */
  875.       /* This is in accordance with the Posix 1003.1 standard,
  876.          section B.7.2.4, which says that trying to set the terminal
  877.          process group with tcsetpgrp() to an unused pgrp value (like
  878.          this would have for the first child) is an error.  Section
  879.          B.4.3.3, p. 237 also covers this, in the context of job control
  880.          shells. */
  881.       if (setpgid (mine, pipeline_pgrp) < 0)
  882.         fprintf (stderr, "%s: child setpgid (%d to %d) error %d: %s\n",
  883.              shell_name, mine, pipeline_pgrp, errno,
  884.              (char *)strerror (errno));
  885.       if (pipeline_pgrp == mine)
  886.         {
  887.           if (!async_p)
  888.         give_terminal_to (pipeline_pgrp);
  889.  
  890. #if defined (PGRP_PIPE)
  891.           pipe_read (pgrp_pipe);
  892. #endif
  893.         }
  894.     }
  895.       else            /* Without job control... */
  896.     {
  897.       if (!pipeline_pgrp)
  898.         pipeline_pgrp = shell_pgrp;
  899.  
  900.       /* If these signals are set to SIG_DFL, we encounter the curious
  901.          situation of an interactive ^Z to a running process *working*
  902.          and stopping the process, but being unable to do anything with
  903.          that process to change its state.  On the other hand, if they
  904.          are set to SIG_IGN, jobs started from scripts do not stop when
  905.          the shell running the script gets a SIGTSTP and stops. */
  906.  
  907.       signal (SIGTSTP, SIG_DFL);
  908.       signal (SIGTTOU, SIG_DFL);
  909.       signal (SIGTTIN, SIG_DFL);
  910.  
  911.       if (async_p)
  912.         {
  913.           signal (SIGINT, SIG_IGN);
  914.           signal (SIGQUIT, SIG_IGN);
  915.         }
  916.     }
  917.  
  918. #if defined (PGRP_PIPE)
  919.       /* Release the process group pipe, since our call to setpgid ()
  920.      is done.  The last call to pipe_close is done in stop_pipeline. */
  921.       pipe_close (pgrp_pipe);
  922. #endif /* PGRP_PIPE */
  923.  
  924.       if (async_p)
  925.     last_asynchronous_pid = getpid ();
  926.     }
  927.   else
  928.     {
  929.       /* In the parent.  Remember the pid of the child just created
  930.      as the proper pgrp if this is the first child. */
  931.  
  932.       if (job_control)
  933.     {
  934.       if (!pipeline_pgrp)
  935.         {
  936.           pipeline_pgrp = pid;
  937.           /* Don't twiddle terminal pgrps in the parent!  This is the bug,
  938.          not the good thing of twiddling them in the child! */
  939.           /* give_terminal_to (pipeline_pgrp); */
  940.         }
  941.       /* This is done on the recommendation of the Rationale section of
  942.          the POSIX 1003.1 standard, where it discusses job control and
  943.          shells.  It is done to avoid possible race conditions. (Ref.
  944.          1003.1 Rationale, section B.4.3.3, page 236). */
  945.       setpgid (pid, pipeline_pgrp);
  946.     }
  947.       else
  948.     {
  949.       if (!pipeline_pgrp)
  950.         pipeline_pgrp = shell_pgrp;
  951.     }
  952.  
  953.       /* Place all processes into the jobs array regardless of the
  954.      state of job_control. */
  955.       add_process (command, pid);
  956.  
  957.       if (async_p)
  958.     last_asynchronous_pid = pid;
  959.  
  960.       last_made_pid = pid;
  961.     }
  962.  
  963.   sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
  964.   return (pid);
  965. }
  966.  
  967. /* When we end a job abnormally, or if we stop a job, we set the tty to the
  968.    state kept in here.  When a job ends normally, we set the state in here
  969.    to the state of the tty. */
  970.  
  971. #if defined (NEW_TTY_DRIVER)
  972. static struct sgttyb shell_tty_info;
  973. static struct tchars shell_tchars;
  974. static struct ltchars shell_ltchars;
  975. #endif /* NEW_TTY_DRIVER */
  976.  
  977. #if defined (TERMIO_TTY_DRIVER)
  978. static struct termio shell_tty_info;
  979. #endif /* TERMIO_TTY_DRIVER */
  980.  
  981. #if defined (TERMIOS_TTY_DRIVER)
  982. static struct termios shell_tty_info;
  983. #endif /* TERMIOS_TTY_DRIVER */
  984.  
  985. #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
  986. /* Since the BSD tty driver does not allow us to change the tty modes
  987.    while simultaneously waiting for output to drain and preserving
  988.    typeahead, we have to drain the output ourselves before calling
  989.    ioctl.  We cheat by finding the length of the output queue, and
  990.    using select to wait for an appropriate length of time.  This is
  991.    a hack, and should be labeled as such (it's a hastily-adapted
  992.    mutation of a `usleep' implementation).  It's only reason for
  993.    existing is the flaw in the BSD tty driver. */
  994.  
  995. static int ttspeeds[] =
  996. {
  997.   0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
  998.   1800, 2400, 4800, 9600, 19200, 38400
  999. };
  1000.  
  1001. static void
  1002. draino (fd, ospeed)
  1003.      int fd, ospeed;
  1004. {
  1005.   register int delay = ttspeeds[ospeed];
  1006.   int n;
  1007.  
  1008.   if (!delay)
  1009.     return;
  1010.  
  1011.   while ((ioctl (fd, TIOCOUTQ, &n) == 0) && n)
  1012.     {
  1013.       if (n > (delay / 100))
  1014.     {
  1015.       struct timeval tv;
  1016.  
  1017.       n *= 10;        /* 2 bits more for conservativeness. */
  1018.       tv.tv_sec = n / delay;
  1019.       tv.tv_usec = ((n % delay) * 1000000) / delay;
  1020.       select (fd, 0, (fd_set *) 0, (fd_set *) 0, (fd_set *) 0, &tv);
  1021.     }
  1022.       else
  1023.     break;
  1024.     }
  1025. }
  1026. #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
  1027.  
  1028. /* Return the fd from which we are actually getting input.  Should be
  1029.    inlined by the compiler. */
  1030. static int
  1031. input_tty ()
  1032. {
  1033.   int tty = shell_tty;
  1034.  
  1035.   if (tty == -1)
  1036.     tty = fileno (stdin);
  1037.  
  1038.   return (tty);
  1039. }
  1040.  
  1041. /* Fill the contents of shell_tty_info with the current tty info. */
  1042. get_tty_state ()
  1043. {
  1044.   int tty = input_tty ();
  1045.  
  1046.   if (tty != -1)
  1047.     {
  1048. #if defined (NEW_TTY_DRIVER)
  1049.       ioctl (tty, TIOCGETP, &shell_tty_info);
  1050.       ioctl (tty, TIOCGETC, &shell_tchars);
  1051.       ioctl (tty, TIOCGLTC, &shell_ltchars);
  1052. #endif /* NEW_TTY_DRIVER */
  1053.  
  1054. #if defined (TERMIO_TTY_DRIVER)
  1055.       ioctl (tty, TCGETA, &shell_tty_info);
  1056. #endif /* TERMIO_TTY_DRIVER */
  1057.  
  1058. #if defined (TERMIOS_TTY_DRIVER)
  1059.       if (tcgetattr (tty, &shell_tty_info) < 0)
  1060.     {
  1061.       extern int shell_level;
  1062.  
  1063.       fprintf (stderr, "%s: [%d: %d] tcgetattr: %s\n", shell_name,
  1064.            getpid (), shell_level, (char *)strerror (errno));
  1065.     }
  1066. #endif /* TERMIOS_TTY_DRIVER */
  1067.     }
  1068. }
  1069.  
  1070. /* Make the current tty use the state in shell_tty_info. */
  1071. set_tty_state ()
  1072. {
  1073.   int tty = input_tty ();
  1074.  
  1075.   if (tty != -1)
  1076.     {
  1077. #if defined (NEW_TTY_DRIVER)
  1078. #  if defined (DRAIN_OUTPUT)
  1079.       draino (tty, shell_tty_info.sg_ospeed);
  1080. #  endif /* DRAIN_OUTPUT */
  1081.       ioctl (tty, TIOCSETN, &shell_tty_info);
  1082.       ioctl (tty, TIOCSETC, &shell_tchars);
  1083.       ioctl (tty, TIOCSLTC, &shell_ltchars);
  1084. #endif /* NEW_TTY_DRIVER */
  1085.  
  1086. #if defined (TERMIO_TTY_DRIVER)
  1087.       ioctl (tty, TCSETAW, &shell_tty_info);
  1088. #endif /* TERMIO_TTY_DRIVER */
  1089.  
  1090. #if defined (TERMIOS_TTY_DRIVER)
  1091.       if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
  1092.     {
  1093.       extern int shell_level;
  1094.  
  1095.       fprintf (stderr, "%s: [%d: %d] tcsetattr: %s\n", shell_name,
  1096.            getpid (), shell_level, (char *)strerror (errno));
  1097.     }
  1098. #endif /* TERMIOS_TTY_DRIVER */
  1099.     }
  1100. }
  1101.  
  1102. /* Given an index into the jobs array JOB, return the pid of the last
  1103.    process in that job's pipeline.  This is the one whose exit status
  1104.    counts. */
  1105. static pid_t
  1106. last_pid (job)
  1107.      int job;
  1108. {
  1109.   register PROCESS *p;
  1110.   sigset_t set, oset;
  1111.  
  1112.   BLOCK_CHILD (set, oset);
  1113.  
  1114.   p = jobs[job]->pipe;
  1115.   while (p->next != jobs[job]->pipe)
  1116.     p = p->next;
  1117.  
  1118.   UNBLOCK_CHILD (oset);
  1119.   return (p->pid);
  1120. }
  1121.  
  1122. /* Wait for a particular child of the shell to finish executing.
  1123.    This low-level function prints an error message if PID is not
  1124.    a child of this shell.  It returns -1 if it fails, or 0 if not. */
  1125. int
  1126. wait_for_single_pid (pid)
  1127.      pid_t pid;
  1128. {
  1129.   register PROCESS *child;
  1130.  
  1131.   child = find_pipeline (pid);
  1132.  
  1133.   if (!child)
  1134.     {
  1135.       report_error ("wait: pid %d is not a child of this shell", pid);
  1136.       return (127);
  1137.     }
  1138.  
  1139.   return (wait_for (pid));
  1140. }
  1141.  
  1142. /* Wait for all of the backgrounds of this shell to finish. */
  1143. void
  1144. wait_for_background_pids ()
  1145. {
  1146.   while (1)
  1147.     {
  1148.       register int i, count = 0;
  1149.       sigset_t set, oset;
  1150.  
  1151.       BLOCK_CHILD (set, oset);
  1152.  
  1153.       for (i = 0; i < job_slots; i++)
  1154.     if (jobs[i] && (JOBSTATE (i) == JRUNNING) && !(jobs[i]->foreground))
  1155.       {
  1156.         count++;
  1157.         break;
  1158.       }
  1159.  
  1160.       if (!count)
  1161.     {
  1162.       UNBLOCK_CHILD (oset);
  1163.       break;
  1164.     }
  1165.  
  1166.       for (i = 0; i < job_slots; i++)
  1167.     if (jobs[i] && (JOBSTATE (i) == JRUNNING) && !jobs[i]->foreground)
  1168.       {
  1169.         pid_t pid = last_pid (i);
  1170.         UNBLOCK_CHILD (oset);
  1171.         QUIT;
  1172.         wait_for_single_pid (pid);
  1173.         break;
  1174.       }
  1175.     }
  1176. }
  1177.  
  1178. /* Wait for pid (one of our children) to terminate, then
  1179.    return the termination state. */
  1180. int
  1181. wait_for (pid)
  1182.      pid_t pid;
  1183. {
  1184.   extern int last_command_exit_value;
  1185.   int job, termination_state;
  1186.   register PROCESS *child;
  1187.   sigset_t set, oset;
  1188.   
  1189.   BLOCK_CHILD (set, oset);
  1190.   termination_state = last_command_exit_value;
  1191.  
  1192.   /* If we say wait_for (), then we have a record of this child somewhere.
  1193.      If this child and all of its peers are not running, then don't
  1194.      sigpause (), since there is no need to. */
  1195.  wait_loop:
  1196.  
  1197.   /* If the shell is running interactively, and the shell is the foreground
  1198.      process (e.g. executing a `wait' command) then let the user C-c out. */
  1199.   if (interactive && (terminal_pgrp == shell_pgrp))
  1200.     QUIT;
  1201.  
  1202.   child = find_pipeline (pid);
  1203.  
  1204.   if (!child)
  1205.     {
  1206.       give_terminal_to (shell_pgrp);
  1207.       UNBLOCK_CHILD (oset);
  1208.       programming_error ("wait_for: No record of pid %d", pid);
  1209.     }
  1210.  
  1211.   /* If this child is part of a job, then we are really waiting for the
  1212.      job to finish.  Otherwise, we are waiting for the child to finish. */
  1213.  
  1214.   job = find_job (pid);
  1215.  
  1216.   if (job != NO_JOB)
  1217.     {
  1218.       register int job_state = 0, any_stopped = 0;
  1219.       register PROCESS *p = jobs[job]->pipe;
  1220.  
  1221.       do
  1222.     {
  1223.       job_state |= p->running;
  1224.       if (!p->running)
  1225.         any_stopped |= WIFSTOPPED (p->status);
  1226.       p = p->next;
  1227.     }
  1228.       while (p != jobs[job]->pipe);
  1229.  
  1230.       if (job_state == 0)
  1231.     {
  1232.       if (any_stopped)
  1233.         jobs[job]->state = JSTOPPED;
  1234.       else
  1235.         jobs[job]->state = JDEAD;
  1236.     }
  1237.     }
  1238.  
  1239.   if (child->running ||
  1240.       ((job != NO_JOB) && (JOBSTATE (job) == JRUNNING)))
  1241.     {
  1242. #if !defined (SCO)
  1243.       sigset_t set;
  1244.  
  1245.       sigemptyset (&set);
  1246.       sigsuspend (&set);
  1247. #else /* SCO Unix */
  1248.       struct sigaction act, oact;
  1249.  
  1250.       act.sa_handler = SIG_DFL;
  1251.       sigemptyset (&act.sa_mask);
  1252.       act.sa_flags = 0;
  1253.  
  1254.       sigaction (SIGCHLD, &act, &oact);
  1255.       flush_child (0);
  1256.       sigaction (SIGCHLD, &oact, (struct sigaction *)NULL);
  1257. #endif /* !SCO */
  1258.  
  1259.       goto wait_loop;
  1260.     }
  1261.  
  1262.   /* The exit state of the command is either the termination state of the
  1263.      child, or the termination state of the job.  If a job, the status
  1264.      of the last child in the pipeline is the significant one. */
  1265.  
  1266.   if (job != NO_JOB)
  1267.     {
  1268.       register PROCESS *p = jobs[job]->pipe;
  1269.  
  1270.       while (p->next != jobs[job]->pipe)
  1271.     p = p->next;
  1272.       if (WIFSIGNALED (p->status))
  1273.     termination_state = 128 + WTERMSIG (p->status);
  1274.       else if (!WIFSTOPPED (p->status))
  1275.     termination_state = WEXITSTATUS (p->status);
  1276.     }
  1277.   else
  1278.     {
  1279.       if (WIFSIGNALED (child->status))
  1280.     termination_state = 128 + WTERMSIG (child->status);
  1281.       else if (!WIFSTOPPED (child->status))
  1282.     termination_state = WEXITSTATUS (child->status);
  1283.     }
  1284.  
  1285.   if (job == NO_JOB || jobs[job]->job_control)
  1286.     give_terminal_to (shell_pgrp);
  1287.  
  1288.   /* If the command did not exit cleanly, or the job is just
  1289.      being stopped, then reset the tty state back to what it
  1290.      was before this command.  Do this only if the shell is
  1291.      interactive. */
  1292.   if (job != NO_JOB && interactive)
  1293.     {
  1294.       if (WIFSIGNALED (child->status) || WIFSTOPPED (child->status))
  1295.     set_tty_state ();
  1296.       else
  1297.     get_tty_state ();
  1298.  
  1299.       notify_and_cleanup ();
  1300.     }
  1301.  
  1302.  wait_exit:
  1303.   UNBLOCK_CHILD (oset);
  1304.   return (termination_state);
  1305. }
  1306.  
  1307. /* Wait for the last process in the pipeline for JOB. */
  1308. int
  1309. wait_for_job (job)
  1310.      int job;
  1311. {
  1312.   pid_t pid = last_pid (job);
  1313.   return (wait_for (pid));
  1314. }
  1315.  
  1316. /* Print info about dead jobs, and then delete them from the list
  1317.    of known jobs. */
  1318. notify_and_cleanup ()
  1319. {
  1320.   if (interactive)
  1321.     notify_of_job_status ();
  1322.   cleanup_dead_jobs ();
  1323. }
  1324.  
  1325. /* Return the next closest (chronologically) job to JOB which is in
  1326.    STATE.  STATE can be JSTOPPED, JRUNNING.  NO_JOB is returned if
  1327.    there is no next recent job. */
  1328. static int
  1329. most_recent_job_in_state (job, state)
  1330.      int job;
  1331.      JOB_STATE state;
  1332. {
  1333.   register int i;
  1334.   sigset_t set, oset;
  1335.  
  1336.   BLOCK_CHILD (set, oset);
  1337.  
  1338.   for (i = job - 1; i >= 0; i--)
  1339.     {
  1340.       if (jobs[i])
  1341.     {
  1342.       if (JOBSTATE (i) == state)
  1343.         {
  1344.           /* Found it! */
  1345.           UNBLOCK_CHILD (oset);
  1346.           return (i);
  1347.         }
  1348.     }
  1349.     }
  1350.   UNBLOCK_CHILD (oset);
  1351.   return (NO_JOB);
  1352. }
  1353.  
  1354. /* Return the newest *stopped* job older than JOB, or NO_JOB if not
  1355.    found. */
  1356. static int
  1357. last_stopped_job (job)
  1358.      int job;
  1359. {
  1360.   return (most_recent_job_in_state (job, JSTOPPED));
  1361. }
  1362.  
  1363. /* Return the newest *running* job older than JOB, or NO_JOB if not
  1364.    found. */
  1365. static int
  1366. last_running_job (job)
  1367.      int job;
  1368. {
  1369.   return (most_recent_job_in_state (job, JRUNNING));
  1370. }
  1371.  
  1372. /* Make JOB be the current job, and make previous be useful. */
  1373. static void
  1374. set_current_job (job)
  1375.      int job;
  1376. {
  1377.   int candidate = NO_JOB;
  1378.  
  1379.   if (current_job != job)
  1380.     {
  1381.       previous_job = current_job;
  1382.       current_job = job;
  1383.     }
  1384.  
  1385.   /* First choice for previous_job is the old current_job. */
  1386.   if (previous_job != current_job &&
  1387.       previous_job != NO_JOB &&
  1388.       jobs[previous_job] &&
  1389.       JOBSTATE (previous_job) == JSTOPPED)
  1390.     return;
  1391.  
  1392.   /* Second choice:  Newest stopped job that is older than
  1393.      the current job. */
  1394.   if (JOBSTATE (current_job) == JSTOPPED)
  1395.     {
  1396.       candidate = last_stopped_job (current_job);
  1397.  
  1398.       if (candidate != NO_JOB)
  1399.     {
  1400.       previous_job = candidate;
  1401.       return;
  1402.     }
  1403.     }
  1404.  
  1405.   /* If we get here, there is either only one stopped job, in which case it is
  1406.      the current job and the previous job should be set to the newest running
  1407.      job, or there are only running jobs and the previous job should be set to
  1408.      the newest running job older than the current job.  We decide on which
  1409.      alternative to use based on whether or not JOBSTATE(current_job) is
  1410.      JSTOPPED. */
  1411.  
  1412.   if (JOBSTATE (current_job) == JRUNNING)
  1413.     candidate = last_running_job (current_job);
  1414.   else
  1415.     candidate = last_running_job (job_slots);
  1416.  
  1417.   if (candidate != NO_JOB)
  1418.     {
  1419.       previous_job = candidate;
  1420.       return;
  1421.     }
  1422.  
  1423.   /* There is only a single job, and it is both `+' and `-'. */
  1424.   previous_job = current_job;
  1425. }
  1426.  
  1427. /* Make current_job be something useful, if it isn't already. */
  1428.  
  1429. /* Here's the deal:  The newest non-running job should be `+', and the
  1430.    next-newest non-running job should be `-'.  If there is only a single
  1431.    stopped job, the previous_job is the newest non-running job.  If there
  1432.    are only running jobs, the newest running job is `+' and the
  1433.    next-newest running job is `-'. */
  1434. static void
  1435. reset_current ()
  1436. {
  1437.   int candidate = NO_JOB;
  1438.  
  1439.   if (current_job != NO_JOB &&
  1440.       job_slots && jobs[current_job] &&
  1441.       JOBSTATE (current_job) == JSTOPPED)
  1442.     {
  1443.       candidate = current_job;
  1444.     }
  1445.   else
  1446.     {
  1447.       /* First choice: the previous job! */
  1448.       if (previous_job != NO_JOB && jobs[previous_job] &&
  1449.       JOBSTATE (previous_job) == JSTOPPED)
  1450.     candidate = previous_job;
  1451.  
  1452.       /* Second choice: the most recently stopped job. */
  1453.       if (candidate == NO_JOB)
  1454.     candidate = last_stopped_job (job_slots);
  1455.  
  1456.       if (candidate == NO_JOB)
  1457.     {
  1458.       /* Third choice: the newest running job. */
  1459.       candidate = last_running_job (job_slots);
  1460.     }
  1461.     }
  1462.  
  1463.   /* If we found a job to use, then use it.  Otherwise, there
  1464.      are no jobs period. */
  1465.   if (candidate != NO_JOB)
  1466.     set_current_job (candidate);
  1467.   else
  1468.     current_job = previous_job = NO_JOB;
  1469. }
  1470.  
  1471. /* Start a job.  FOREGROUND if non-zero says to do that.  Otherwise,
  1472.    start the job in the background.  JOB is a zero-based index into
  1473.    JOBS.  Returns -1 if it is unable to start a job, and the return
  1474.    status of the job otherwise. */
  1475. int
  1476. start_job (job, foreground)
  1477.      int job, foreground;
  1478. {
  1479.   register PROCESS *p;
  1480.   int already_running;
  1481.   sigset_t set, oset;
  1482.   char *wd;
  1483. #if defined (NEW_TTY_DRIVER)
  1484.   static struct sgttyb save_stty;
  1485. #endif
  1486.  
  1487. #if defined (TERMIO_TTY_DRIVER)
  1488.   static struct termio save_stty;
  1489. #endif
  1490.  
  1491. #if defined (TERMIOS_TTY_DRIVER)
  1492.   static struct termios save_stty;
  1493. #endif
  1494.  
  1495.   BLOCK_CHILD (set, oset);
  1496.   already_running = (JOBSTATE (job) == JRUNNING);
  1497.  
  1498.   if (!foreground && already_running)
  1499.     {
  1500.       extern char *this_command_name;
  1501.  
  1502.       report_error ("%s: bg background job?", this_command_name);
  1503.       UNBLOCK_CHILD (oset);
  1504.       return (-1);
  1505.     }
  1506.  
  1507.   wd = job_working_directory ();
  1508.  
  1509.   /* You don't know about the state of this job.  Do you? */
  1510.   jobs[job]->notified = 0;
  1511.  
  1512.   if (foreground)
  1513.     {
  1514.       set_current_job (job);
  1515.       jobs[job]->foreground = 1;
  1516.     }
  1517.  
  1518.   /* Tell the outside world what we're doing. */
  1519.   p = jobs[job]->pipe;
  1520.  
  1521.   if (!foreground)
  1522.     fprintf (stderr, "[%d]%c ", job + 1,
  1523.        (job == current_job) ? '+': ((job == previous_job) ? '-' : ' '));
  1524.  
  1525.   do
  1526.     {
  1527.       fprintf (stderr, "%s%s",
  1528.            p->command, p->next != jobs[job]->pipe? " | " : "");
  1529.       p = p->next;
  1530.     }
  1531.   while (p != jobs[job]->pipe);
  1532.  
  1533.   if (!foreground)
  1534.     fprintf (stderr, " &");
  1535.  
  1536.   if (strcmp (wd, jobs[job]->wd) != 0)
  1537.     fprintf (stderr, "    (wd: %s)", polite_directory_format (jobs[job]->wd));
  1538.  
  1539.   fprintf (stderr, "\n");
  1540.  
  1541.   free (wd);
  1542.  
  1543.   /* Run the job. */
  1544.   if (!already_running)
  1545.     {
  1546.       /* Each member of the pipeline is now running. */
  1547.       p = jobs[job]->pipe;
  1548.  
  1549.       do
  1550.     {
  1551.       if (WIFSTOPPED (p->status))
  1552.         p->running = 1;
  1553.       p = p->next;
  1554.     }
  1555.       while (p != jobs[job]->pipe);
  1556.  
  1557.       /* This means that the job is running. */
  1558.       JOBSTATE (job) = JRUNNING;
  1559.     }
  1560.  
  1561.   /* Save the tty settings before we start the job in the foreground. */
  1562.   if (foreground)
  1563.     {
  1564.       get_tty_state ();
  1565.       save_stty = shell_tty_info;
  1566.     }
  1567.  
  1568.   /* Give the terminal to this job. */
  1569.   if (foreground)
  1570.     {
  1571.       if (jobs[job]->job_control)
  1572.     give_terminal_to (jobs[job]->pgrp);
  1573.     }
  1574.   else
  1575.     jobs[job]->foreground = 0;
  1576.  
  1577.   /* If the job is already running, then don't bother jump-starting it. */
  1578.   if (!already_running)
  1579.     {
  1580.       jobs[job]->notified = 1;
  1581.       killpg (jobs[job]->pgrp, SIGCONT);
  1582.     }
  1583.  
  1584.   UNBLOCK_CHILD (oset);
  1585.  
  1586.   if (foreground)
  1587.     {
  1588.       pid_t pid = last_pid (job);
  1589.       int s = wait_for (pid);
  1590.  
  1591.       shell_tty_info = save_stty;
  1592.       set_tty_state ();
  1593.       return (s);
  1594.     }
  1595.   else
  1596.     {
  1597.       reset_current ();
  1598.       return (0);
  1599.     }
  1600. }
  1601.  
  1602. /* Give PID SIGNAL.  This determines what job the pid belongs to (if any).
  1603.    If PID does belong to a job, and the job is stopped, then CONTinue the
  1604.    job after giving it SIGNAL.  Returns -1 on failure.  If GROUP is non-null,
  1605.    then kill the process group associated with PID. */
  1606. int
  1607. kill_pid (pid, signal, group)
  1608.      pid_t pid;
  1609.      int signal, group;
  1610. {
  1611.   register PROCESS *p;
  1612.   int job, result = EXECUTION_SUCCESS;
  1613.   sigset_t set, oset;
  1614.  
  1615.   BLOCK_CHILD (set, oset);
  1616.   p = find_pipeline (pid);
  1617.   job = find_job (pid);
  1618.  
  1619.   if (group)
  1620.     {
  1621.       if (job != NO_JOB)
  1622.     {
  1623.       jobs[job]->notified = 0;
  1624.  
  1625.       /* Kill process in backquotes or one started without job control? */
  1626.       if (jobs[job]->pgrp == shell_pgrp)
  1627.         {
  1628.           p = jobs[job]->pipe;
  1629.  
  1630.           do
  1631.         {
  1632.           kill (p->pid, signal);
  1633.           if (!p->running && (signal == SIGTERM || signal == SIGHUP))
  1634.             kill (p->pid, SIGCONT);
  1635.           p = p->next;
  1636.         } while (p != jobs[job]->pipe);
  1637.         }
  1638.       else
  1639.         {
  1640.           result = killpg (jobs[job]->pgrp, signal);
  1641.           if (p && (JOBSTATE (job) == JSTOPPED) &&
  1642.           (signal == SIGTERM || signal == SIGHUP))
  1643.         killpg (jobs[job]->pgrp, SIGCONT);
  1644.         }
  1645.     }
  1646.       else
  1647.     {
  1648.       result = killpg (pid, signal);
  1649.     }
  1650.     }
  1651.   else
  1652.     {
  1653.       result = kill (pid, signal);
  1654.     }
  1655.   UNBLOCK_CHILD (oset);
  1656.   return (result);
  1657. }
  1658.  
  1659. /* Take care of system dependencies that must be handled when waiting for
  1660.    children.  The arguments to the WAITPID macro match those to the Posix.1
  1661.    waitpid() function. */
  1662.  
  1663. #if defined (Ultrix) && defined (mips) && defined (_POSIX_VERSION)
  1664. #  define WAITPID(pid, statusp, options) \
  1665.     wait3 ((union wait *)statusp, options, (struct rusage *)0)
  1666. #else
  1667. #  if defined (_POSIX_VERSION)
  1668. #    define WAITPID(pid, statusp, options) \
  1669.     waitpid ((pid_t)pid, statusp, options)
  1670. #  else
  1671. #    if defined (hpux)
  1672. #      define WAITPID(pid, statusp, options) \
  1673.     wait3 (statusp, options, (int *)0)
  1674. #    else
  1675. #      define WAITPID(pid, statusp, options) \
  1676.     wait3 (statusp, options, (struct rusage *)0)
  1677. #    endif /* !hpux */
  1678. #  endif /* !_POSIX_VERSION */
  1679. #endif /* !(Ultrix && mips && _POSIX_VERSION) */
  1680.  
  1681. /* If the system needs it, REINSTALL_SIGCHLD_HANDLER will reinstall the
  1682.    handler for SIGCHLD. */
  1683.  
  1684. #if defined (hpux) && !defined (_POSIX_VERSION)
  1685. #  define REINSTALL_SIGCHLD_HANDLER signal (SIGCHLD, flush_child)
  1686. #else
  1687. #  define REINSTALL_SIGCHLD_HANDLER
  1688. #endif /* !hpux || _POSIX_VERSION */
  1689.  
  1690. /* Flush_child () flushes at least one of the children that we are waiting for.
  1691.    It gets run when we have gotten a SIGCHLD signal, and stops when there
  1692.    aren't any children terminating any more.  If SIG is 0, this is to be a
  1693.    blocking wait for a single child.  It is here to get around SCO Unix's
  1694.    broken sigsuspend (). */
  1695.  
  1696. static sighandler
  1697. flush_child (sig)
  1698.      int sig;
  1699. {
  1700.   WAIT status;
  1701.   PROCESS *child;
  1702.   pid_t pid;
  1703.   int call_set_current = 0, last_stopped_job = NO_JOB;
  1704.   int children_exited = 0;
  1705.  
  1706.   do
  1707.     {
  1708.       pid = WAITPID (-1, &status, sig ? (WNOHANG | WUNTRACED) : WUNTRACED);
  1709.  
  1710.       if (pid > 0)
  1711.     {
  1712.       REINSTALL_SIGCHLD_HANDLER;
  1713.  
  1714.       /* Locate our PROCESS for this pid. */
  1715.       child = find_pipeline (pid);
  1716.  
  1717.       /* It is not an error to have a child terminate that we did
  1718.          not have a record of.  This child could have been part of
  1719.          a pipeline in backquote substitution. */
  1720.       if (child)
  1721.         {
  1722.           int job = find_job (pid);
  1723.  
  1724.           while (child->pid != pid)
  1725.         child = child->next;
  1726.  
  1727.           /* Remember status, and fact that process is not running. */
  1728.           child->status = status;
  1729.           child->running = 0;
  1730.  
  1731.           if (job != NO_JOB)
  1732.         {
  1733.           int job_state = 0;
  1734.           int any_stopped = 0;
  1735.  
  1736.           child = jobs[job]->pipe;
  1737.           jobs[job]->notified = 0;
  1738.  
  1739.           /* If all children are not running, but any of them is
  1740.              stopped, then the job is stopped, not dead. */
  1741.           do
  1742.            {
  1743.               job_state |= child->running;
  1744.               if (!child->running)
  1745.             any_stopped |= (WIFSTOPPED (child->status));
  1746.               child = child->next;
  1747.             }
  1748.           while (child != jobs[job]->pipe);
  1749.  
  1750.           if (job_state == 0)
  1751.             {
  1752.               if (any_stopped)
  1753.             {
  1754.               jobs[job]->state = JSTOPPED;
  1755.               jobs[job]->foreground = 0;
  1756.               call_set_current++;
  1757.               last_stopped_job = job;
  1758.             }
  1759.               else
  1760.             {
  1761.               jobs[job]->state = JDEAD;
  1762.  
  1763.               if (job == last_stopped_job)
  1764.                 last_stopped_job = NO_JOB;
  1765.  
  1766.               /* If this job was not started with job control,
  1767.                  then the shell has already seen the SIGINT, since
  1768.                  the process groups are the same.  In that case,
  1769.                  don't send the SIGINT to the shell; it will
  1770.                  surprise people to have a stray interrupt
  1771.                  arriving some time after they killed the job. */
  1772.  
  1773.               /* XXX - should the `|| interactive' be there? */
  1774.               if (jobs[job]->foreground &&
  1775.                   (jobs[job]->job_control || interactive) &&
  1776.                   WTERMSIG (jobs[job]->pipe->status) == SIGINT)
  1777.                 kill (getpid (), SIGINT);
  1778.             }
  1779.             }
  1780.         }
  1781.         }
  1782.       /* If we have caught a child, and a trap was set for SIGCHLD, then
  1783.          bump up the count of the number of children that have exited,
  1784.          so we know how many times to call it. */
  1785.       children_exited++;
  1786.     }
  1787.     }
  1788. #if defined (SCO)
  1789.   while (sig && pid > (pid_t)0);   /* Hack for SCO, see earlier comment. */
  1790. #else
  1791.   while (pid > (pid_t)0);
  1792. #endif /* SCO */
  1793.  
  1794.   /* If a job was running and became stopped, then set the current
  1795.      job.  Otherwise, don't change a thing. */
  1796.   if (call_set_current)
  1797.     if (last_stopped_job != NO_JOB)
  1798.       set_current_job (last_stopped_job);
  1799.     else
  1800.       reset_current ();
  1801.  
  1802.   /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
  1803.   {
  1804.     extern char *trap_list[];
  1805.  
  1806.     if ((trap_list[SIGCHLD] != (char *)DEFAULT_SIG) &&
  1807.     (trap_list[SIGCHLD] != (char *)IGNORE_SIG))
  1808.       {
  1809.     extern int last_command_exit_value;
  1810.     /* It's quite dangerous to do this from a signal handler, so
  1811.        we turn off the trap list temporarily while we parse and
  1812.        execute the command.  This will protect us against (potentially
  1813.        infinite) recursive calls.  We also preserve $? around the
  1814.        execution of trap commands, by saving and restoring the value
  1815.        of last_command_exit_value. */
  1816.  
  1817.     char *trap_command = trap_list[SIGCHLD];
  1818.     int old_exit_value = last_command_exit_value;
  1819.     trap_list[SIGCHLD] = (char *)DEFAULT_SIG;
  1820.     while (children_exited--)
  1821.       parse_and_execute (savestring (trap_command), "trap");
  1822.     trap_list[SIGCHLD] = trap_command;
  1823.     last_command_exit_value = old_exit_value;
  1824.       }
  1825.   }
  1826.  
  1827.   /* We have successfully recorded the useful information about this process
  1828.      that has just changed state.  If we notify asynchronously, and the job
  1829.      that this process belongs to is no longer running, then notify the user
  1830.      of that fact now. */
  1831.   if (asynchronous_notification && interactive)
  1832.     notify_of_job_status ();
  1833.  
  1834. #if !defined (VOID_SIGHANDLER)
  1835.   return (0);
  1836. #endif /* VOID_SIGHANDLER */
  1837. }
  1838.  
  1839. /* Function to call when you want to notify people of changes
  1840.    in job status.  This prints out all jobs which are pending
  1841.    notification to stderr, and marks those printed as already
  1842.    notified, thus making them candidates for cleanup. */
  1843. static void
  1844. notify_of_job_status ()
  1845. {
  1846.   register int job, termsig;
  1847.   char *dir = job_working_directory ();
  1848.   sigset_t set, oset;
  1849.  
  1850.   sigemptyset (&set);
  1851.   sigaddset (&set, SIGCHLD);
  1852.   sigaddset (&set, SIGTTOU);
  1853.   sigemptyset (&oset);
  1854.   sigprocmask (SIG_BLOCK, &set, &oset);
  1855.  
  1856.   for (job = 0; job < job_slots; job++)
  1857.     {
  1858.       if (jobs[job] && jobs[job]->notified == 0)
  1859.     {
  1860.       WAIT s;
  1861.  
  1862.       s = jobs[job]->pipe->status;
  1863.       termsig = WTERMSIG (s);
  1864.  
  1865.       switch (JOBSTATE (job))
  1866.         {
  1867.           /* Print info on jobs that are running in the background,
  1868.          and on foreground jobs that were killed by anything
  1869.          except SIGINT. */
  1870.  
  1871.         case JDEAD:
  1872.  
  1873.           if (jobs[job]->foreground)
  1874.         {
  1875.           if (termsig && WIFSIGNALED (s) && termsig != SIGINT)
  1876.             {
  1877.               fprintf (stderr, "%s", sys_siglist[termsig]);
  1878.  
  1879.               if (WIFCORED (s))
  1880.             fprintf (stderr, " (core dumped)");
  1881.  
  1882.               fprintf (stderr, "\n");
  1883.             }
  1884.         }
  1885.           else
  1886.         {
  1887.           pretty_print_job (job, 0, stderr);
  1888.           if (dir && strcmp (dir, jobs[job]->wd) != 0)
  1889.             fprintf (stderr,
  1890.                  "(wd now: %s)\n", polite_directory_format (dir));
  1891.         }
  1892.           jobs[job]->notified = 1;
  1893.           break;
  1894.  
  1895.         case JSTOPPED:
  1896.           fprintf (stderr, "\n");
  1897.           pretty_print_job (job, 0, stderr);
  1898.           if (dir && (strcmp (dir, jobs[job]->wd) != 0))
  1899.         fprintf (stderr,
  1900.              "(wd now: %s)\n", polite_directory_format (dir));
  1901.           jobs[job]->notified = 1;
  1902.           break;
  1903.  
  1904.         case JRUNNING:
  1905.         case JMIXED:
  1906.           break;
  1907.  
  1908.         default:
  1909.           programming_error ("notify_of_job_status");
  1910.         }
  1911.     }
  1912.     }
  1913.   free (dir);
  1914.   sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
  1915. }
  1916.  
  1917. /* getpgrp () varies between systems.  Even systems that claim to be
  1918.    Posix.1 compatible lie sometimes (Ultrix, SunOS4, apollo). */
  1919. #if defined (_POSIX_VERSION) && !defined (BSD_GETPGRP)
  1920. #  define getpgid(p) getpgrp ()
  1921. #else
  1922. #  define getpgid(p) getpgrp (p)
  1923. #endif /* !_POSIX_VERSION || BSD_GETPGRP */
  1924.  
  1925. /* Initialize the job control mechanism, and set up the tty stuff. */
  1926. initialize_jobs ()
  1927. {
  1928.   shell_pgrp = getpgid (0);
  1929.  
  1930.   if (shell_pgrp == -1)
  1931.     {
  1932.       fprintf (stderr, "%s: initialize_jobs: getpgrp failed: %s\n",
  1933.            shell_name, (char *)strerror (errno));
  1934.       exit (1);
  1935.     }
  1936.  
  1937.   /* We can only have job control if we are interactive?
  1938.      I guess that makes sense. */
  1939.  
  1940.   if (!interactive)
  1941.     {
  1942.       job_control = 0;
  1943.     }
  1944.   else
  1945.     {
  1946.       /* Make sure that we are using the new line discipline. */
  1947.  
  1948.       /* Get our controlling terminal.  If job_control is set, or
  1949.      interactive is set, then this is an interactive shell no
  1950.      matter what opening /dev/tty returns.  (It sometimes says
  1951.      the wrong thing.) */
  1952. #if !defined (SCO)
  1953.       /* SCO Unix fails attempting job control on /dev/tty. */
  1954.       if ((shell_tty = open ("/dev/tty", O_RDWR, 0666)) < 0)
  1955. #endif /* !SCO */
  1956.     shell_tty = dup (fileno (stdin));
  1957.  
  1958.       /* Find the highest unused file descriptor we can. */
  1959.       {
  1960.     int ignore, nds = getdtablesize ();
  1961.  
  1962.     while (--nds > 3)
  1963.       {
  1964.         if (fcntl (nds, F_GETFD, &ignore) == -1)
  1965.           break;
  1966.       }
  1967.  
  1968.     if (shell_tty != nds && (dup2 (shell_tty, nds) != -1))
  1969.       {
  1970.         if (shell_tty != fileno (stdin))
  1971.           close (shell_tty);
  1972.         shell_tty = nds;
  1973.       }
  1974.       }
  1975.  
  1976. #if defined (NeXT)
  1977.       /* Compensate for a bug in the NeXT 2.0 /usr/etc/rlogind. */
  1978.       if (shell_pgrp == 0)
  1979.     {
  1980.       shell_pgrp = getpid ();
  1981.       setpgid (0, shell_pgrp);
  1982.       tcsetpgrp (shell_tty, shell_pgrp);
  1983.     }
  1984. #endif /* NeXT */
  1985.  
  1986.       while ((terminal_pgrp = tcgetpgrp (shell_tty)) != -1)
  1987.     {
  1988.       if (shell_pgrp != terminal_pgrp)
  1989.         {
  1990.           SigHandler *old_ttin = (SigHandler *)signal (SIGTTIN, SIG_DFL);
  1991.           kill (0, SIGTTIN);
  1992.           signal (SIGTTIN, old_ttin);
  1993.           continue;
  1994.         }
  1995.       break;
  1996.     }
  1997.  
  1998.       if (set_new_line_discipline (shell_tty) < 0)
  1999.     {
  2000.       fprintf (stderr, "%s: initialize_jobs: line discipline: %s",
  2001.            shell_name, (char *)strerror (errno));
  2002.       job_control = 0;
  2003.     }
  2004.       else
  2005.     {
  2006.       original_pgrp = shell_pgrp;
  2007.       shell_pgrp = getpid ();
  2008.  
  2009.       if ((original_pgrp != shell_pgrp) &&
  2010.           (setpgid (0, shell_pgrp) < 0))
  2011.         {
  2012.           fprintf (stderr, "%s: initialize_jobs: setpgid: %s\n",
  2013.                shell_name, (char *)strerror (errno));
  2014.  
  2015.           shell_pgrp = original_pgrp;
  2016.         }
  2017.  
  2018.       job_control = 1;
  2019.       give_terminal_to (shell_pgrp);
  2020.     }
  2021.     }
  2022.  
  2023.   if (shell_tty != fileno (stdin))
  2024.     SET_CLOSE_ON_EXEC (shell_tty);
  2025.  
  2026. #if !defined (_POSIX_VERSION)
  2027.   signal (SIGCHLD, flush_child);
  2028. #else
  2029.   /* Some Posix job control implementations (like SCO 3.2.x) set signals to
  2030.      call sigaction with NOCLDSTOP set in sa_flags.  Make sure we get
  2031.      signalled on child status changes by using sigaction instead of
  2032.      signal. */
  2033.   {
  2034.     struct sigaction act;
  2035.     act.sa_handler = flush_child;
  2036.     sigemptyset (&act.sa_mask);
  2037.     sigaddset (&act.sa_mask, SIGCHLD);
  2038.     act.sa_flags = 0;
  2039.     sigaction (SIGCHLD, &act, (struct sigaction *)NULL);
  2040.   }
  2041. #endif /* _POSIX_VERSION */
  2042.  
  2043.   change_flag_char ('m', job_control ? '-' : '+');
  2044.  
  2045.   if (interactive)
  2046.     get_tty_state ();
  2047. }
  2048.  
  2049. /* Set the line discipline to the best this system has to offer.
  2050.    Return -1 if this is not possible. */
  2051. static int
  2052. set_new_line_discipline (tty)
  2053.      int tty;
  2054. {
  2055. #if defined (NEW_TTY_DRIVER)
  2056.   int ldisc;
  2057.  
  2058.   if (ioctl (tty, TIOCGETD, &ldisc) < 0)
  2059.     return (-1);
  2060.  
  2061.   if (ldisc != NTTYDISC)
  2062.     {
  2063.       ldisc = NTTYDISC;
  2064.  
  2065.       if (ioctl (tty, TIOCSETD, &ldisc) < 0)
  2066.     return (-1);
  2067.     }
  2068.   return (0);
  2069. #endif /* NEW_TTY_DRIVER */
  2070.  
  2071. #if defined (TERMIO_TTY_DRIVER)
  2072. #  if defined (NTTYDISC)
  2073.   if (ioctl (tty, TCGETA, &shell_tty_info) < 0)
  2074.     return (-1);
  2075.  
  2076.   if (shell_tty_info.c_line != NTTYDISC)
  2077.     {
  2078.       shell_tty_info.c_line = NTTYDISC;
  2079.       if (ioctl (tty, TCSETAW, &shell_tty_info) < 0)
  2080.     return (-1);
  2081.     }
  2082. #  endif /* NTTYDISC */
  2083.   return (0);
  2084. #endif /* TERMIO_TTY_DRIVER */
  2085.  
  2086. #if defined (TERMIOS_TTY_DRIVER)
  2087. #if defined (Ultrix) || defined (SunOS4)
  2088.   if (tcgetattr (tty, &shell_tty_info) < 0)
  2089.     return (-1);
  2090.  
  2091.   if (shell_tty_info.c_line != NTTYDISC)
  2092.     {
  2093.       shell_tty_info.c_line = NTTYDISC;
  2094.       if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
  2095.     return (-1);
  2096.     }
  2097. #endif /* Ultrix || SunOS4 */
  2098.   return (0);
  2099. #endif /* TERMIOS_TTY_DRIVER */
  2100.  
  2101. #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
  2102.   return (-1);
  2103. #endif
  2104. }
  2105.  
  2106. /* Allow or disallow job control to take place.  Returns the old value
  2107.    of job_control. */
  2108. int
  2109. set_job_control (arg)
  2110.      int arg;
  2111. {
  2112.   int old;
  2113.  
  2114.   old = job_control;
  2115.   job_control = arg;
  2116.   return (old);
  2117. }
  2118.  
  2119. static SigHandler *old_tstp, *old_ttou, *old_ttin;
  2120. static SigHandler *old_cont = (SigHandler *)SIG_DFL;
  2121. static sighandler stop_signal_handler (), cont_signal_handler ();
  2122.  
  2123. /* Setup this shell to handle C-C, etc. */
  2124. initialize_job_signals ()
  2125. {
  2126.   sighandler sigint_sighandler ();
  2127.  
  2128.   if (interactive)
  2129.     {
  2130.       signal (SIGINT, sigint_sighandler);
  2131.       signal (SIGTSTP, SIG_IGN);
  2132.       signal (SIGTTOU, SIG_IGN);
  2133.       signal (SIGTTIN, SIG_IGN);
  2134.     }
  2135.   else if (job_control)
  2136.     {
  2137.       old_tstp = (SigHandler *)signal (SIGTSTP, stop_signal_handler);
  2138.       old_ttou = (SigHandler *)signal (SIGTTOU, stop_signal_handler);
  2139.       old_ttin = (SigHandler *)signal (SIGTTIN, stop_signal_handler);
  2140.     }
  2141.   /* Leave these things alone for non-interactive shells without job
  2142.      control. */
  2143. }
  2144.  
  2145. /* Here we handle CONT signals. */
  2146. static sighandler
  2147. cont_signal_handler (sig)
  2148.      int sig;
  2149. {
  2150.   initialize_job_signals ();
  2151.   signal (SIGCONT, old_cont);
  2152.   kill (getpid (), SIGCONT);
  2153.  
  2154. #if !defined (VOID_SIGHANDLER)
  2155.   return (0);
  2156. #endif /* VOID_SIGHANDLER */
  2157. }
  2158.  
  2159. /* Here we handle stop signals while we are running not as a login shell. */
  2160. static sighandler
  2161. stop_signal_handler (sig)
  2162.      int sig;
  2163. {
  2164.   signal (SIGTSTP, old_tstp);
  2165.   signal (SIGTTOU, old_ttou);
  2166.   signal (SIGTTIN, old_ttin);
  2167.  
  2168.   old_cont = (SigHandler *)signal (SIGCONT, cont_signal_handler);
  2169.  
  2170.   give_terminal_to (shell_pgrp);
  2171.  
  2172.   kill (getpid (), sig);
  2173.  
  2174. #if !defined (VOID_SIGHANDLER)
  2175.   return (0);
  2176. #endif /* VOID_SIGHANDLER */
  2177. }
  2178.  
  2179. /* Give the terminal to PGRP.  */
  2180. give_terminal_to (pgrp)
  2181.      pid_t pgrp;
  2182. {
  2183.   sigset_t set, oset;
  2184.  
  2185.   if (job_control)
  2186.     {
  2187.       sigemptyset (&set);
  2188.       sigaddset (&set, SIGTTOU);
  2189.       sigaddset (&set, SIGTTIN);
  2190.       sigaddset (&set, SIGTSTP);
  2191.       sigaddset (&set, SIGCHLD);
  2192.       sigemptyset (&oset);
  2193.       sigprocmask (SIG_BLOCK, &set, &oset);
  2194.  
  2195.       if (tcsetpgrp (shell_tty, pgrp) < 0)
  2196.     {
  2197.       /* Maybe we should print an error message? */
  2198.     }
  2199.       else
  2200.     terminal_pgrp = pgrp;
  2201.  
  2202.       sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
  2203.     }
  2204. }
  2205.  
  2206. /* Clear out any jobs in the job array.  This is intended to be used by
  2207.    children of the shell, who should not have any job structures as baggage
  2208.    when they start executing (forking subshells for parenthesized execution
  2209.    and functions with pipes are the two that spring to mind). */
  2210. delete_all_jobs ()
  2211. {
  2212.   if (job_slots)
  2213.     {
  2214.       register int i;
  2215.  
  2216.       current_job = previous_job = NO_JOB;
  2217.  
  2218.       for (i = 0; i < job_slots; i++)
  2219.     if (jobs[i] != (JOB *) NULL)
  2220.       delete_job (i);
  2221.  
  2222.       free ((char *)jobs);
  2223.       job_slots = 0;
  2224.     }
  2225. }
  2226.  
  2227. /* Turn off all traces of job control.  This is run by children of the shell
  2228.    which are going to do shellsy things, like wait (), etc. */
  2229. without_job_control ()
  2230. {
  2231.   stop_making_children ();
  2232.   start_pipeline ();
  2233.   delete_all_jobs ();
  2234.   set_job_control (0);
  2235. }
  2236.  
  2237. #if defined (PGRP_PIPE)
  2238. /* Read from the read end of a pipe.  This is how the process group leader
  2239.    blocks until all of the processes in a pipeline have been made. */
  2240. static void
  2241. pipe_read (pp)
  2242.      int *pp;
  2243. {
  2244.   char ch;
  2245.  
  2246.   if (pp[1] >= 0)
  2247.     {
  2248.       close (pp[1]);
  2249.       pp[1] = -1;
  2250.     }
  2251.  
  2252.   if (pp[0] >= 0)
  2253.     {
  2254.       while (read (pp[0], &ch, 1) == -1 && errno == EINTR)
  2255.     continue;
  2256.     }
  2257. }
  2258.  
  2259. /* Close the read and write ends of PP, an array of file descriptors. */
  2260. static void
  2261. pipe_close (pp)
  2262.      int *pp;
  2263. {
  2264.   if (pp[0] >= 0)
  2265.     close (pp[0]);
  2266.  
  2267.   if (pp[1] >= 0)
  2268.     close (pp[1]);
  2269.  
  2270.   pp[0] = pp[1] = -1;
  2271. }
  2272.  
  2273. /* Functional interface closes our local-to-job-control pipes. */
  2274. close_pgrp_pipe ()
  2275. {
  2276.   pipe_close (pgrp_pipe);
  2277. }
  2278.  
  2279. #endif /* PGRP_PIPE */
  2280.  
  2281. #endif /* JOB_CONTROL */
  2282.